<?php 
namespace app\authorization\controller;
use think\Controller;
use think\Validate;
use app\authorization\model\ApiUserModel as AUM ;
use app\authorization\model\ModuleModel as MM;
use app\admin\model\ModulePluginModel;

/**
 * 子系统用户操作
 */
class ApiOperateController extends Controller
{
	/**
	 * 请求参数
	 */
	private static $param = [];
	/**
	 * 用户信息
	 */
	private static $user ;
	/**
	 * apiUser操纵模型
	 */
	private $apiUserModel ;

	/**
	 * 用户token携带的用户数据  sub用户id
	 */
	private static $playload ;

	/**
	 * 控制器初始化方法
	 */
	public function _initialize()
	{	
		$param = $this->request->param();
		//$param = $this->test();
		if( !isset( $param['param'] ) || empty( $param [ 'param' ] ) ){
			return api_json_echo( false , '未正确传递参数信息' , null , 100 );
		}
		if( !isset( $param['param'][ 'type' ] ) || empty( $param['param'][ 'type' ] )  ){
			return api_json_echo( false , '未知的操作类型' , null , 101 );
		}
		self::$param = $param [ 'param' ] ;

		$this->apiUserModel = new AUM();

		/**
		 * token 为全局通信许可证
		 * 用户需要先验证信息,拿到许可证
		 */

		//允许通过的请求 首次激活, 激活反馈.获取token
		$ALLOW_REQUEST = [ '1020042101' , '2220042102' , '2020542105' ];

		//1.用户未拥有许可证
		if( !isset( $param['token'] ) || empty( $param [ 'token' ] ) ){
			//如果是默许操作放行,否则拒绝请求
			if ( !in_array( self::$param [ 'type' ] , $ALLOW_REQUEST ) ) {
				return api_json_echo( false , '无效的请求' , null , 102 );
			}
			//默许放行的请求,执行有效信息验证
			if( !isset( $param['proof'] ) || empty( $param [ 'proof' ] ) ){
				return api_json_echo( false , '未检测到凭证信息' , null , 10001 );
			}
			//凭证检测
			$res = $this->checkProof( $param [ 'proof' ] );
			if(  isset( $res ['status'] ) && $res [ 'status' ] == false ){
				return api_json_echo( false , $res [ 'message' ] , null , $res [ 'code' ] );
			}
			//返回用户信息
			self::$user = $res; 
		}else{
			//携带token的请求   校验许可证
			$res = $this->apiUserModel->verifyToken( $param [ 'token' ] );
			if( isset( $res['status'] ) && $res [ 'status' ] == false  ){
				//校验失败 返回结果
				return api_json_echo( false , $res [ 'message' ] , null , $res [ 'code' ] );
			}
			//校验通过 $playLoad 的 sub 保存的是用户id 获取到用户id 以便后续操作
			self::$playload = $res;

			//执行后续操作,入口方法:entrance() 
		}
	}

	private function test()
	{
		$param = [
			'proof' => [
				'appid' => '4a661eb7e93e76f53df55066780f3a72',
				'uid' => md5('weiwei###ec65a0eb2ff413573878729149a93f4f'),
				//user_verify_encodeKey( $appsecret , $userName , $num1 , $num2 )
				'key' => user_verify_encodeKey( 'ffe220bb7a009fb1732d9647c089fd60' , 'weiwei' , 3 , 23 )."0323"
			],
			'param' => [
				'type'=>'2030042103',
				'store_id' => 53
			],
			'token'	=> 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJmYWZkNGNmOGM2NDhkYTFhYTg2MzM4ZDRhNTE1MjI5NCIsImlhdCI6MTU4ODIxNzE3MiwiZXhwIjoxNTg4MjI0MzcyLCJzdWIiOiIyNDMiLCJzdWJwd2QiOiIjIyNlYzY1YTBlYjJmZjQxMzU3Mzg3ODcyOTE0OWE5M2Y0ZiIsImp0aSI6IjlmOTFkOWQ4Y2FkOWM2Y2E2MDk1ZTdmYmM2M2IyN2Y3In0.zP9_WZuRKOUSJouddNZFYSw8HEhNGJ2d2heFwPQ_Xcc',
		] ;

		return $param ;
	}

	/**
	 * 检查用户信息
	 */
	private function checkProof( $proof )
	{
		if( !isset( $proof[ 'appid' ] ) || empty( $proof[ 'appid' ] )  ){
			return api_json_echo( false , 'appid不存在' , null , 20001 );
		}
		if( !isset( $proof[ 'uid' ] ) || empty( $proof[ 'uid' ] )  ){
			return api_json_echo( false , 'uid不存在' , null , 20002 );
		}
		if( !isset( $proof[ 'key' ] ) || empty( $proof[ 'key' ] )  ){
			return api_json_echo( false , 'key不存在' , null , 20003 );
		}

		$res = $this->apiUserModel->checkInput( $proof );
		return $res;
	}


	/**
	 * 子系统用户操作行为入口方法
	 */
	public function entrance()
	{
		$actionType = [
			'1020042101' 	=>	 	'active',
			'2220042102' 	=>	 	'activeSuccess',
			'2030042103' 	=>	 	'getMenu',
			'2024042104'	=>		'modifyPwd',
			'2020542105'	=>		'createToken',
			'2020052806'	=>		'getModuleList',
			'2020042907'	=>		'getModuleLoadAddr',
			'2020043008'	=>		'moduleInstall',
			'2020043009'	=>		'moduleUninstall',
			'2020050410'	=>		'moduleUpdate',
			'2020050411' 	=>		'moduleUpdateMenu',
			'2020062812'	=>		'getPluginLoadAddr',
			'2020062813'	=>		'getPluginList',		

		];
		if( !isset( self::$param[ 'type' ] ) || empty( self::$param[ 'type' ] )  ){
			return api_json_echo( false , '未知的操作类型' , null , 101 );
		}
		if( !isset( $actionType[ self::$param[ 'type' ] ] ) ){
			return api_json_echo( false , '未知的操作类型' , null , 101 );
		}

		$this->$actionType[ self::$param[ 'type' ] ]();
	}

	/**
	 * 创建token
	 */
	private function createToken()
	{
		$token = $this->apiUserModel->createToken( self::$user[ 'user_id' ] , self::$user[ 'user_pass' ] );

		if( isset( $token [ 'status' ] ) && $token['status'] == false ){
			return api_json_echo( false , $token['message'] , null , $token[ 'code' ] );
		}
		return api_json_echo( true , 'OK' , [ 'token' => $token ] );
	}
	
	private function active()
	{
		$this->userActive( 'scjh' );
	}
	
	private function activeSuccess()
	{
		$this->userActive( 'jhfk' );
	}
	

	/**
	 * 激活操作
	 */
	private function userActive( $isActive = 'scjh' )
	{
		$this->apiUserModel->type = 'scjh';

		if( $isActive == 'scjh' ){
			//首次激活
			$res = $this->apiUserModel->getUserInfo( self::$user['user_id'] );
			if( isset( $res [ 'status' ] ) && $res['status'] == false ){
				return api_json_echo( false , $res['message'] , null , 10002 );
			}
			return api_json_echo( true , 'OK' , $res );

		}else if( $isActive == 'jhfk' ){
			//激活反馈
			$res = $this->apiUserModel->updateActiveStatus( self::$user['user_id'] );
			if( isset( $res [ 'status' ] ) && $res['status'] == false ){
				return api_json_echo( false , $res['message'] , null , 10003 );
			}
			return api_json_echo( true , 'OK' );
		}
	}

	/**
	 * 获取授权菜单
	 */
	private function getMenu()
	{
		$res = $this->apiUserModel->getMenu( self::$playload['sub'] );
		if( isset( $res [ 'status' ] ) && $res['status'] == false ){
			return api_json_echo( false , $res['message'] , null , $res['code'] );
		}
		return api_json_echo( true , 'OK' , $res );
	}

	/**
	 * 修改密码
	 */
	private function modifyPwd()
	{
		if( !isset( self::$param[ 'old' ] ) || empty( self::$param[ 'old' ] )  ){
			return api_json_echo( false , '原密码不存在' , null , 101 );
		}

		if( !isset( self::$param[ 'new' ] ) || empty( self::$param[ 'new' ] )  ){
			return api_json_echo( false , '新密码不存在' , null , 102 );
		}

		if( self::$param[ 'old' ] == self::$param[ 'new' ]  ){
			return api_json_echo( false , '新密码不能和旧密码一样' , null , 107 );
		}

		$validate = new Validate([
			'old' => 'require',
			'new' => 'require|min:6|max:25',
		]);

		if( !$validate->check( self::$param ) ){
			return api_json_echo( false , $validate->getError() , null , 103 );
		}
		$res = $this->apiUserModel->modifyPwd( self::$playload['sub'] , self::$param );
		if( isset( $res [ 'status' ] ) && $res['status'] == false ){
			return api_json_echo( false , $res [ 'message' ] , null , 104 );
		}
		if( !$res ){
			return api_json_echo( false , '修改失败,请稍后再试' , 106 );
		}
		return api_json_echo( true , '修改成功' );
	}


	//模块操作
	///////////////////////////////////////////////////////////////////////////////////
	/**
	 * 获取授权的模块列表
	 */
	public function getModuleList()
	{
		$userId = self::$playload[ 'sub' ];
		$mm = new MM();
		$res = $mm->getModuleList( $userId );
		return api_json_echo( true , 'OK' , $res );
	}
	
	//获取插件列表
	public function getPluginList()
	{
		if( !isset( self::$param[ 'store_id' ] ) || empty( self::$param[ 'store_id' ] )  ){
			return api_json_echo( false , '无效的模块标识' , null , 100 );
		}
		$mid = self::$param[ 'store_id' ];
		$list = ModulePluginModel::where( 'mid' , $mid )->select();
		return api_json_echo( true , 'ok' , $list );
		
	}

	/**
	 * 获取模块下载地址
	 */
	public function getModuleLoadAddr()
	{
		if( !isset( self::$param[ 'store_id' ] ) || empty( self::$param[ 'store_id' ] )  ){
			return api_json_echo( false , '无效的模块标识' , null , 100 );
		}
		$store = self::$param[ 'store_id' ];
		$mm = new MM();
		$res = $mm->getDownLoadAddrHost();
		if( isset( $res [ 'status' ] ) && $res['status'] == false ){
			return api_json_echo( false , $res [ 'message' ] , null , $res['code'] );
		}
		$module = $mm->getModuleInfo( $store );
		if( isset( $module [ 'status' ] ) && $module['status'] === false ){
			return api_json_echo( false , $module [ 'message' ] , null , $module['code'] );
		}
		return api_json_echo( true , 'OK' , urlencode( $res.'/'.$module[ 'resource' ] ) );
	}
	
	// 获取插件下载地址
	public function getPluginLoadAddr()
	{
		if(  !isset( self::$param[ 'p_id' ] ) || empty( self::$param[ 'p_id' ] )  ){
			return api_json_echo( false , '无效的插件标识 ' , null , 100 );
		}
		$p_id = self::$param[ 'p_id' ];
		
		$mm = new MM();
		$res = $mm->getDownLoadAddrHost();
		
		if( isset( $res [ 'status' ] ) && $res['status'] == false ){
			return api_json_echo( false , $res [ 'message' ] , null , $res['code'] );
		}
		
		$plugin = ModulePluginModel::get($p_id);
		if( !$plugin ){
			return api_json_echo( false , '记录不存在' , null , 101 );
		}
		return api_json_echo( true , 'OK' , urlencode( $res.'/'.$plugin[ 'resource' ] ) );
	}

	/**
	 * 模块安装操作
	 */
	public function moduleInstall()
	{
		if( !isset( self::$param[ 'store_id' ] ) || empty( self::$param[ 'store_id' ] )  ){
			return api_json_echo( false , '无效的模块标识' , null , 11005 );
		}
		$mm = new MM();
		$res = $mm->moduleInstall( self::$param [ 'store_id' ] , self::$playload[ 'sub' ] );
		if( isset( $res [ 'status' ] ) && $res['status'] == false ){
			return api_json_echo( false , $res [ 'message' ] , null , $res['code'] );
		}

		return api_json_echo( true , '模块安装成功' , [ 'code' => $res ] );
	}


	/**
	 * 模块卸载
	 */
	public function moduleUninstall()
	{
		if( !isset( self::$param[ 'store_id' ] ) || empty( self::$param[ 'store_id' ] )  ){
			return api_json_echo( false , '无效的模块标识' , null , 11005 );
		}
		$mm = new MM();
		$res = $mm->moduleUninstall( self::$param [ 'store_id' ] , self::$playload[ 'sub' ] );
		if( isset( $res [ 'status' ] ) && $res['status'] == false ){
			return api_json_echo( false , $res [ 'message' ] , null , $res['code'] );
		}
		return api_json_echo( true , '模块卸载成功' );
	}

	/**
	 * 模块更新菜单
	 */
	public function moduleUpdateMenu()
	{
		if( !isset( self::$param[ 'code' ] ) || empty( self::$param[ 'code' ] )  ){
			return api_json_echo( false , '无效的CODE' , null , 11009 );
		}
		if( !isset( self::$param[ 'menu' ] ) || empty( self::$param[ 'menu' ] )  ){
			return api_json_echo( false , '未检索到菜单信息' , null , 11012 );
		}

		$mm = new MM();
		$res = $mm->moduleUpdateMenu( self::$playload [ 'sub' ] , self::$param [ 'code' ] , self::$param['menu'] );
		if( isset( $res [ 'status' ] ) && $res['status'] == false ){
			return api_json_echo( false , $res [ 'message' ] , null , $res['code'] );
		}
		return api_json_echo( true , '模块菜单更新成功' );
	}

}